#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
from typing import Dict, Any, Type

from document_processor.engines.base_engine import BaseEngine
from document_processor.engines.marker_engine import MarkerEngine
from document_processor.engines.markitdown_engine import MarkItDownEngine
from document_processor.engines.mineru_engine import MinerUEngine
from document_processor.engines.pdfminer_engine import PDFMinerEngine
from document_processor.engines.word_engine import WordEngine

logger = logging.getLogger(__name__)

class EngineFactory:
    """文档处理引擎工厂类
    
    用于创建和管理不同的文档处理引擎。支持引擎的注册和获取。
    """
    
    # 存储已注册的引擎类
    _engines: Dict[str, Type[BaseEngine]] = {}
    
    @classmethod
    def register_engine(cls, name: str, engine_class: Type[BaseEngine]) -> None:
        """注册引擎
        
        Args:
            name: 引擎名称
            engine_class: 引擎类
        """
        if not issubclass(engine_class, BaseEngine):
            raise ValueError(f"引擎类 {engine_class.__name__} 必须是 BaseEngine 的子类")
            
        if name in cls._engines:
            logger.warning(f"引擎 '{name}' 已存在，将被覆盖")
        
        cls._engines[name] = engine_class
        logger.info(f"已注册引擎：{name}")
    
    @classmethod
    def get_engine(cls, name: str, config: Dict[str, Any]) -> BaseEngine:
        """获取引擎实例
        
        Args:
            name: 引擎名称
            config: 配置字典
            
        Returns:
            引擎实例
            
        Raises:
            ValueError: 如果引擎不存在或配置无效
        """
        if not isinstance(config, dict):
            raise ValueError("配置必须是字典类型")
            
        if "document" not in config:
            raise ValueError("配置中缺少 'document' 部分")
            
        if "supported_formats" not in config["document"]:
            raise ValueError("配置中缺少 'document.supported_formats'")
            
        if name not in cls._engines:
            raise ValueError(f"未知引擎：{name}，当前已注册引擎：{list(cls._engines.keys())}")
        
        engine_class = cls._engines[name]
        try:
            engine = engine_class(config)
            logger.info(f"成功创建引擎实例：{name}")
            return engine
        except Exception as e:
            logger.error(f"创建引擎实例失败：{name}, 错误：{str(e)}")
            raise

    @classmethod
    def register_default_engines(cls) -> None:
        """注册默认引擎"""
        try:
            # 注册基础引擎
            cls.register_engine("markitdown", MarkItDownEngine)
            cls.register_engine("pdfminer", PDFMinerEngine)
            cls.register_engine("word", WordEngine)
            cls.register_engine("mineru", MinerUEngine)
            cls.register_engine("marker", MarkerEngine)
            logger.info(f"已注册默认引擎: {list(cls._engines.keys())}")
        except Exception as e:
            logger.error(f"注册默认引擎失败：{str(e)}")

# 在模块加载时注册默认引擎
EngineFactory.register_default_engines() 